import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { BLUR_COMMAND, KEY_ESCAPE_COMMAND } from "lexical";
import { useEffect } from "react";

export function OnBlurOrFocusPlugin() {
  const [editor] = useLexicalComposerContext();

  useEffect(() => {
    const unregisterBlur = editor.registerCommand(
      BLUR_COMMAND,
      () => {
        editor.dispatchCommand(
          KEY_ESCAPE_COMMAND,
          new KeyboardEvent("keydown", {
            key: "Escape",
          }),
        );
        return false;
      },
      1,
    );

    return () => {
      unregisterBlur();
    };
  }, [editor]);

  return null;
}
